﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SQLServerHealthCheck.Model;

namespace SQLServerHealthCheck.SQLServer.IssueTypes
{
    public class PerformanceCheckTableNoPrimayKey : IssueTypeCheckBase
    {

        public PerformanceCheckTableNoPrimayKey()
        {
            IssueTypeId = 5001;
        }

        public override void Check()
        {
            HealthCheckDataContext dc = new HealthCheckDataContext(System.Configuration.ConfigurationManager.AppSettings["ConnectionStringSSHCDatabase"]);
            Issue issue;

            // This Query gets all tables that does not have a PK

            var QryTable = from t in dc.Tables
                      where t.Indexes.Count(i => i.IS_PK == true) > 0
                      && Convert.ToInt32(t.TotalSize) > 100 * 1024
                      select t;  

          

            foreach (var item in QryTable)
            {
                
                //Get Issuetype object

                issue = new Issue();

                //Get Issuetype object  And return first issue Id
                IssueType issueType = dc.IssueTypes.FirstOrDefault(i => i.IssueTypeId == IssueTypeId);

                issue.IssueType = issueType;
                issue.TargetId = item.TableID;
                

                issue.Description = issueType.Description.Replace("{DatabaseName}", item.Database.DatabaseName).Replace("{TableName}", item.TableName);

                dc.Issues.InsertOnSubmit(issue);




            }


            dc.SubmitChanges();



        }



    }

}
